package zip;

import Util.CreateFileUtil;
import com.github.luben.zstd.Zstd;
import com.github.luben.zstd.ZstdDictCompress;
import com.github.luben.zstd.ZstdDictDecompress;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Setup;

import java.util.Base64;
import java.util.HashMap;


/**
 * JDK ZSTD test
 */
public class ZSTDTest extends TestParent {
    // 压缩等级，以时间换空间
    @Param({"1", "2", "3", "4", "5", "6", "7", "8", "9"})
    public int LEVEL;

    // 解压时字节数组的最大值:20MB
    @Param({"20971520"})
    public int MAX_SIZE;

    private ZstdDictCompress compressDict;
    private ZstdDictDecompress decompressDict;

    static HashMap<Integer, byte[]> compressFile;
    static HashMap<Integer, byte[]> deCompressFile;
    static {
        compressFile = new HashMap<Integer, byte[]>();
        deCompressFile = new HashMap<Integer, byte[]>();
        for (int i = 1; i < 10; i++) {
            compressFile.put(i,CreateFileUtil.getBytesByFile("./test/test_"+i+".json"));
            deCompressFile.put(i,CreateFileUtil.getBytesByFile("./test/test_"+i+".ZSTD"));
        }
    }

    @Setup
    public void setup() {
        // 初始化词典对象
        byte[] zd = CreateFileUtil.getBytesByFile("./zd.json");
        // 初始化词典对象
        assert zd != null;
        compressDict = new ZstdDictCompress(zd, LEVEL);
        decompressDict = new ZstdDictDecompress(zd);
    }

//    @Benchmark
    public byte[] compress() {
        byte[] out = Base64.getEncoder().encode(Zstd.compress(compressFile.get(LEVEL), compressDict));;
        CreateFileUtil.bytes2File(out,"./test/","test_"+LEVEL+".ZSTD");
        return out;
    }

    @Benchmark
    public byte[] deCompress() {
        byte[] in = Base64.getDecoder().decode(deCompressFile.get(LEVEL));
        byte[] out = Zstd.decompress(in, decompressDict, (int)Zstd.decompressedSize(in));
        CreateFileUtil.bytes2File(out,"./test/","test_"+LEVEL+".ZSTD.json");
        return out;
    }
}
